<template>
  <div>
    <el-dialog
      width="80%"
      top="10vh"
      :title="title"
      :visible.sync="importVisible"
      :before-close="handleClose"
    >
      <el-form
        class="formView"
        ref="form"
        label-position="right"
        :model="formdata"
        label-width="120px"
      >
        <el-form-item style="margin-right:40px;" label="下载模版：">
          <el-button
            type="text"
            @click="exportExcel"
            :loading="exportButtomLoading"
            >{{ templateInfo }}</el-button
          >
        </el-form-item>
        <el-form-item label="选择上传文件：">
          <el-upload
            class="upload-demo"
            :action="exportExcelUrl"
            :on-preview="handlePreview"
            :headers="headerObj"
            :data="formdata"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleImg"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button type="text">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="scrollWrapper">
        <el-table
          v-if="importDetailShow"
          class="tableContent"
          show-summary
          :before-close="handleClose"
          :summary-method="getSummaries"
          height="60vh"
          :data="importDetail.orderList"
          style="width: 100%; "
        >
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column
            prop="purchaseOrderNo"
            label="订单单号"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column
            prop="salesOrderNo"
            label="订单单号"
            width="120px"
            v-if="downLoadType == 2"
          ></el-table-column>
          <el-table-column
            prop="companyId"
            label="公司ID"
            width="120px"
          ></el-table-column>
          <el-table-column
            prop="companyName"
            label="公司名称"
            width="120px"
          ></el-table-column>
          <el-table-column
            prop="shopName"
            label="门店"
            v-if="downLoadType == 2"
          ></el-table-column>
          <el-table-column
            prop="repositoryName"
            label="仓库"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column
            prop="productName"
            label="货品名称"
          ></el-table-column>
          <el-table-column prop="specText" label="规格"></el-table-column>
          <el-table-column
            prop="primaryUnitName"
            label="主单位"
          ></el-table-column>
          <el-table-column prop="subUnitName" label="副单位"></el-table-column>
          <el-table-column
            prop="multiple"
            label="主副单位倍数"
          ></el-table-column>
          <el-table-column
            prop="purchaseUnitName"
            label="采购单位"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column
            prop="salesUnitName"
            label="售卖单位"
            v-if="downLoadType == 2"
          ></el-table-column>
          <el-table-column
            prop="supplierName"
            label="供应商名称"
            width="120"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column
            prop="customerName"
            label="客户名称"
            width="120"
            v-if="downLoadType == 2"
          ></el-table-column>
          <el-table-column
            prop="supplierPhoneNo"
            label="手机号"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column
            prop="customerPhoneNo"
            label="手机号"
            v-if="downLoadType == 2"
          ></el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column prop="orderType" label="结算方式"></el-table-column>
          <el-table-column prop="payType" label="支付渠道"></el-table-column>
          <el-table-column
            prop="primaryNumber"
            label="主单位采购数量"
          ></el-table-column>
          <el-table-column
            prop="subNumber"
            label="副单位采购数量"
          ></el-table-column>
          <el-table-column
            prop="purchasePrice"
            label="采购单价(¥)"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column
            prop="salesPrice"
            label="销售单价(¥)"
            v-if="downLoadType == 2"
          ></el-table-column>
          <el-table-column
            prop="orderAmount"
            label="总金额(¥)"
          ></el-table-column>
          <el-table-column
            prop="purchaseUserName"
            label="采购员"
            v-if="downLoadType == 1"
          ></el-table-column>
          <el-table-column
            prop="salesUserName"
            label="销售员"
            v-if="downLoadType == 2"
          ></el-table-column>
        </el-table>
        <div
          class="tips"
          v-if="
            importDetailShow && !readonly && importDetail.downLoadStatus != 1
          "
        >
          温馨提示：部分异常数据导入失败，请点击“下载异常数据”查看异常数据！
        </div>
      </div>
      <div slot="footer" v-if="importDetailShow">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button
          type="primary"
          v-if="!readonly && importDetail.downLoadStatus != 1"
          @click="downLoad"
          >下载异常数据</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { downLoadExcel } from '@/api/user'
export default {
  components: {},
  computed: {
    ...mapGetters([
      'name',
      'roles',
      'defaultCompany',
      'shops',
      'companys',
      'userInfo'
    ])
  },
  props: {
    templateInfo: {
      type: String,
      default() {
        return ''
      }
    },
    title: {
      type: String,
      default() {
        return ''
      }
    },
    downLoadUrl: {
      type: String,
      default() {
        return ''
      }
    },
    /**
     * 1 批量采购
     * 2 批量销售开单
     */
    downLoadType: {
      type: null,
      default() {
        return 1
      }
    },
    exportExcelUrl: {
      type: String,
      default() {
        return ''
      }
    },
    multipleSelection: {
      type: null,
      default() {
        return []
      }
    },
    readonly: {
      type: Boolean,
      default() {
        return false
      }
    },
    shopId: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      importVisible: false,
      exportButtomLoading: false,
      canNotClose: true,
      formdata: {},
      headerObj: {},
      fileList: [],
      importDetail: {},
      importDetailShow: false,
      datalist: []
    }
  },
  created() {},
  mounted() {
    this.headerObj['snInfo'] = getToken()
    this.headerObj['tagEnd'] = 2
    this.headerObj['source'] = 'pc'
    this.formdata = {
      companyId: this.defaultCompany.companyId
    }
  },
  methods: {
    downLoad() {
      this.canNotClose = false
      window.open(this.importDetail.uploadUrl)
    },
    beforeUpload(file) {
      if (!/.xlsx$/.test(file.name)) {
        this.$message.error('只支持xlsx格式的文件')
        this.fileList = []
        return false
      }
    },
    handleRemove(file, fileList) {
      this.fileList = []
      this.importDetailShow = false
      this.importDetail = {}
      this.canNotClose = false
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`)
    },
    beforeRemove(file, fileList) {
      return (
        /.xlsx$/.test(file.name) && this.$confirm(`确定移除 ${file.name}？`)
      )
    },
    handleImg(response, file, fileList) {
      this.importDetailShow = true
      this.importDetail = response
      this.canNotClose = !(response.downLoadStatus ^ 0)
    },
    getSummaries(param) {
      const { columns, data } = param
      // console.log(param);
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = this.importDetail.orderList.map(item =>
          Number(item[column.property])
        )
        if (!values.every(value => isNaN(value)) && index === 19) {
          sums[index] = this.importDetail.totalAmount
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    closeDialog() {
      this.canNotClose
        ? this.$message({
            message: '请先下载异常数据',
            type: 'warning'
          })
        : (this.importVisible = false)
    },
    handleClose(done) {
      !this.canNotClose
        ? done()
        : this.$message({
            message: '请先下载异常数据',
            type: 'warning'
          })
    },
    // 下载Excel
    exportExcel() {
      console.log(this.downLoadUrl)
      if (!this.downLoadUrl) {
        return false
      }
      let params = {}
      if (this.downLoadType == 1) {
        // 批量采购下载模版
        params = { companyId: this.defaultCompany.companyId }
      } else if (this.downLoadType == 2) {
        // 批量开单模版
        params = {
          companyId: this.defaultCompany.companyId,
          shopId: this.shopId
        }
      }
      this.exportButtomLoading = true
      downLoadExcel(params, this.downLoadUrl).then(
        res => {
          if (res.uploadUrl) {
            window.open(res.uploadUrl)
            this.$message({
              message: '下载成功',
              type: 'success'
            })
          }
          this.exportButtomLoading = false
        },
        err => {
          this.exportButtomLoading = false
        }
      )
    }
  },
  watch: {
    importVisible: {
      handler(now, old) {
        now &&
          (_ => {
            this.canNotClose = false
            this.importDetailShow = false
            this.fileList = []
            this.importDetail = {}
          })()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog__title {
    font-size: 16px;
  }
  .el-dialog {
    border-radius: 10px;
  }
  .el-dialog__body {
    padding-top: 0;
    padding-bottom: 20px;
  }
  .el-form {
    padding: 10px 0;
  }
  .el-form-item {
    margin-bottom: 0px;
  }
  .upload-demo {
    display: flex;
    flex-direction: row;
    .el-upload-list__item {
      margin-top: 8px;
      margin-left: 10px;
    }
  }
}
.formView {
  display: flex;
  flex-direction: row;
}
.scrollWrapper {
  border-top: 1px solid #eee;
  .dialog-footer {
    text-align: right;
    border-top: 1px solid #eee;
    padding: 10px 0;
  }
  .tips {
    color: red;
    margin-top: 10px;
    margin-left: 5px;
  }
}
</style>
